﻿from django.shortcuts import render
from django.http import JsonResponse
from django.http import HttpResponse

import json
import uuid
import base64
import datetime
import random

from hulin.models import Ranger,Manageuser,Managelogin,Supuser
from hulin.models import Mession,Event,Rjurnal
from hulin.models import Map,Group,Category,Mpoint
from hulin.models import Locus,Signin,Forest
# Create your views here.


#'127.0.0.1:8000/hulin/data/ranger'  获取护林员列表
def get_ranger(request):
    temid= request.GET.get('managerId')
    json_ranger = {"code":0}
    list_ranger=[]
    for i in Ranger.objects.filter(uid__startswith=temid).values('uid','name','sex','status','phone','mid'):
        list_ranger.append(i)
        manager = Manageuser.objects.get(uid = i['mid'])
        list_ranger[-1]['mid'] = manager.name
    json_ranger["data"] = {"list":list_ranger}
    return JsonResponse(json_ranger)

#'127.0.0.1:8000/hulin/data/singleranger'  获取一个护林员的全部信息
def get_singleranger(request):
    temid = request.GET.get('rangerId')
    json_sranger = {"code": 0}
    tendata = Ranger.objects.get(uid = temid)
    json_sranger["data"]={"uid":tendata.uid,"name":tendata.name,"sex":tendata.sex,"photo":tendata.photo,"start":tendata.start,
                          "years":tendata.years,"status":tendata.status,"phone":tendata.phone,"info":tendata.info}
    manager = Manageuser.objects.get(uid=tendata.mid)
    json_sranger["data"]["mid"] = manager.name
    return JsonResponse(json_sranger)

#‘127.0.0.1:8000/hulin/operation/dispatch’    发布一个调度任务
def put_mession(request):
    #验证token
    get_token = request.META.get('HTTP_X_TOKEN')
    stok = base64.b64decode(get_token).decode()
    temmid = Managelogin.objects.get(token=stok).uid
    data = json.loads(request.body)
    if not Managelogin.objects.filter(token=stok).count():
        return JsonResponse({"code":1,"msg":"你不是管理员，请登录"})
    elif temmid != data["rid"]//100:
        return JsonResponse({"code":1,"msg":"该护林员不在你的管辖范围"})
    else :
        #正式流程
        #id编号
        temnum = Mession.objects.filter(rid = data["rid"]).count()
        if temnum == 0:
            temid = data["rid"]*1000
        else:
            temid = Mession.objects.filter(rid=data["rid"])[temnum - 1].id + 1
        temtime = str(datetime.datetime.now())[0:19]
        Mession.objects.create(id=temid,title=data["title"],content=data["content"],x=data["x"],y=data["y"],mclass=data["class"],
                               status='进行中',stime=temtime,rid=data["rid"],mid=temmid)
        #轨迹记录
        temfile = Locus.objects.get(uid = data["rid"])
        j_temfile = eval(temfile.mfile)
        j_temfile[temtime] = [data["x"],data["y"]]
        temfile.mfile = json.dumps(j_temfile)
        temfile.save()
        #管理员记录记录
        temman = Managelogin.objects.get(uid = temmid)
        j_temman = eval(temman.mfile)
        j_temman[temtime] = '我(%d)向%s(%d)发布了任务-%s' % (temmid,Ranger.objects.get(uid = data["rid"]).name,data["rid"],data["title"])
        temman.mfile = json.dumps(j_temman,ensure_ascii=False)
        temman.save()
        #更改护林员状态
        remran = Ranger.objects.get(uid = data["rid"])
        remran.status = '%d个任务进行中' % (remran.num+1)
        remran.num = remran.num+1
        remran.save()
        return JsonResponse({"code":0,"msg":"任务布置成功"})

#‘127.0.0.1:8000/hulin/handle’    处理事件
def put_handle(request):
    #验证token
    get_token = request.META.get('HTTP_X_TOKEN')
    stok = base64.b64decode(get_token).decode()
    temmid = Managelogin.objects.get(token=stok).uid
    data = json.loads(request.body)
    if not Managelogin.objects.filter(token=stok).count():
        return JsonResponse({"code":1,"msg":"你不是管理员，请登录"})
    elif temmid != data["eid"]//100000:
        return JsonResponse({"code":1,"msg":"该事件不在你的管辖范围"})
    else :
        temtime = str(datetime.datetime.now())[0:19]
        teme = Event.objects.get(id = data["eid"])
        teme.ftime = temtime
        teme.handle = data["handle"]
        teme.status = "已处理"
        teme.save()
        # 管理员记录记录
        temman = Managelogin.objects.get(uid=temmid)
        j_temman = eval(temman.mfile)
        j_temman[temtime] = '我(%d)处理了%s(%d)上报的事件-%s' % (temmid, Ranger.objects.get(uid=data["eid"]//1000).name, data["eid"]//1000, teme.title)
        temman.mfile = json.dumps(j_temman, ensure_ascii=False)
        temman.save()
        return JsonResponse({"code":0,"msg":"事件已成功处理"})

#'127.0.0.1:8000/hulin/data/mession'  获取任务列表
def get_mession(request):
    temid = request.GET.get('yourId')
    json_mession = {"code":0}
    list_mession = []
    for i in Mession.objects.filter(id__startswith=temid).values('id','title','content','stime','ftime','x','y','mclass','status','mid','rid'):
        i["mid"] = Manageuser.objects.get(uid=i["mid"]).name
        i["rid"] = Ranger.objects.get(uid=i["rid"]).name
        list_mession.append(i)
    json_mession["data"]={"list":list_mession}
    return JsonResponse(json_mession)

#'127.0.0.1:8000/hulin/data/point'  获取护林员位置
def get_point(request):
    json_point = {"code":0}
    list_point = []
    for i in Mpoint.objects.all():
        i.x = random.randint(max(0,i.x-1000),min(i.x+1000,12032))
        i.y = random.randint(max(0,i.y-1000),min(i.y+1000,10240))
        i.save()
        list_point.append({"id":i.id,"x":i.x,"y":i.y,"rid":i.rid,"name":i.name})
    json_point["data"] = {"list":list_point}
    return JsonResponse(json_point)

#’127.0.0.1:8000/hulin/data/event‘    获取事件列表
def get_event(request):
    temid = request.GET.get('yourId')
    json_event = {"code": 0}
    list_event = []
    for i in Event.objects.filter(id__startswith=temid).values('id','title','content','stime','ftime','x','y','handle','mclass','status','mid','rid'):
        i["mid"] = Manageuser.objects.get(uid=i["mid"]).name
        i["rid"] = Ranger.objects.get(uid=i["rid"]).name
        list_event.append(i)
    json_event["data"] = {"list":list_event}
    return JsonResponse(json_event)

#’127.0.0.1:8000/hulin/data/jurnal‘    获取日志列表
def get_jurnal(request):
    temid = request.GET.get('yourId')
    json_jurnal = {"code": 0}
    list_jurnal = []
    for i in Rjurnal.objects.filter(id__startswith=temid).values('id','time','content','rid'):
        i["rid"] = Ranger.objects.get(uid=i["rid"]).name
        list_jurnal.append(i)
    json_jurnal["data"] = {"list":list_jurnal}
    return JsonResponse(json_jurnal)




#'127.0.0.1:8000/hulin/data/manager'  获取管理员列表
def get_manager(request):
    #get_token = request.META.get('HTTP_X_TOKEN')
    json_manager = {"code":0}
    list_manager = []
    for i in Manageuser.objects.all().values('uid','name'):
        list_manager.append(i)
    json_manager["data"] = {"list":list_manager}
    return JsonResponse(json_manager)

#'127.0.0.1:8000/hulin/add/ranger'  添加新护林员
def add_ranger(request):
    #get_token = request.META.get('HTTP_X_TOKEN')
    data = json.loads(request.body)
    # id编号
    temnum = Ranger.objects.filter(mid=data["mid"]).count()
    if temnum == 0:
        temid = data["mid"] * 100
    else:
        temid = Ranger.objects.filter(mid=data["mid"])[temnum - 1].uid + 1
    tempn = Mpoint.objects.all().count()
    tempid = Mpoint.objects.all()[tempn - 1].id + 1
    Ranger.objects.create(uid=temid, name=data["name"],sex=data["sex"],photo=data["photoUrl"],phone=data["phone"],start=str(datetime.datetime.now())[0:10],
                          years=data["age"],info=data["info"],mid=data["mid"],status='在岗',num=0)
    Mpoint.objects.create(id = tempid,type='point',x=random.randint(0,10000),y=random.randint(0,10000),rid = temid,name = data["name"],gid=100000)
    Locus.objects.create(uid=temid,mfile ='{}')
    Signin.objects.create(uid=temid,lfile="['2022-09-01', '2022-09-02', '2022-09-03', '2022-09-04', '2022-09-05', '2022-09-06', '2022-08-29']")
    return JsonResponse({"code":0,"msg":"添加成功"})

#'127.0.0.1:8000/hulin/del/ranger'  删除护林员
def del_ranger(request):
    # get_token = request.META.get('HTTP_X_TOKEN')
    data = json.loads(request.body)
    Ranger.objects.get(uid=data["rid"]).delete()
    Locus.objects.get(uid=data["rid"]).delete()
    Signin.objects.get(uid=data["rid"]).delete()
    Mpoint.objects.get(rid=data["rid"]).delete()
    return JsonResponse({"code": 0, "msg": "删除成功"})

#'127.0.0.1:8000/hulin/upd/ranger'  修改护林员
def upd_ranger(request):
    # get_token = request.META.get('HTTP_X_TOKEN')
    data = json.loads(request.body)
    temr = Ranger.objects.get(uid=data["rid"])
    temr.name = data["name"]
    temr.years = data["age"]
    temr.sex = data["sex"]
    temr.photo = data["photoUrl"]
    temr.phone = data["phone"]
    temr.info = data["info"]
    temr.save()
    temp = Mpoint.objects.get(rid=data["rid"])
    temp.name = data["name"]
    temp.save()
    return JsonResponse({"code": 0, "msg": "修改成功"})

#'127.0.0.1:8000/hulin/login'     登录
def manager_login(request):
    data = json.loads(request.body)
    if Supuser.objects.filter(uid=data["uid"]).count():
        if Supuser.objects.get(uid=data["uid"]).password == str(base64.b64encode(data["password"].encode())):
            stok = str(uuid.uuid4())  # 存储形式
            temt = Supuser.objects.get(uid=data["uid"])
            temt.token = stok
            temt.save()
            return JsonResponse({"code": 0, "data": {"session_token": str(base64.b64encode(stok.encode()))[2:50]}})
        else:
            return JsonResponse({"code": 1, "msg": "工号或密码错误"})
    if Managelogin.objects.filter(uid = data["uid"]).count():
        if Managelogin.objects.get(uid = data["uid"]).password == str(base64.b64encode(data["password"].encode())):
            stok = str(uuid.uuid4())  # 存储形式
            temt = Managelogin.objects.get(uid=data["uid"])
            temt.token = stok
            temt.save()
            return JsonResponse({"code":0,"data":{"session_token":str(base64.b64encode(stok.encode()))[2:50]}})
        else:
             return JsonResponse({"code":1,"msg":"工号或密码错误"})
    else:
        return JsonResponse({"code": 1, "msg": "工号或密码错误"})

# '127.0.0.1:8000/hulin/judgement'  根据token获取用户权限
def token_judgement(request):
    get_token = request.META.get('HTTP_X_TOKEN')
    stok = base64.b64decode(get_token).decode()
    if Supuser.objects.filter(token = stok).count():
        return JsonResponse({"code":0,"data":{"roles":["superadmin",]}})
    elif Managelogin.objects.filter(token = stok).count():
        return JsonResponse({"code":0,"data":{"roles":["admin",]}})
    else:
        return JsonResponse({"code":1,"masg":"登录过期，重新登录"})

#'127.0.0.1:8000/hulin/logout'     登出
def manager_logout(request):
    get_token = request.META.get('HTTP_X_TOKEN')
    stok = base64.b64decode(get_token).decode()
    if Supuser.objects.filter(token = stok).count():
        tem = Supuser.objects.get(token = stok)
        tem.token = 'aann'
        tem.save()
        return JsonResponse({"code":0,"msg":"退出成功"})
    elif Managelogin.objects.filter(token = stok).count():
        tem = Managelogin.objects.get(token = stok)
        tem.token = 'aann'
        tem.save()
        return JsonResponse({"code":0,"msg":"退出成功"})
    return JsonResponse({"code": 0, "msg": "退出成功"})






#‘127.0.0.1:8000/hulin/locus/ranger'   获取护林员轨迹
def locus_ranger(request):
    temid = request.GET.get('rangerId')
    temfile = Locus.objects.get(uid = temid)
    json_lr = {"code":0}
    json_lr["data"] = list(eval(temfile.mfile).values())
    return JsonResponse(json_lr)

#‘127.0.0.1:8000/hulin/locus/manager'   获取管理员操作记录
def locus_manager(request):
    temid = request.GET.get('managerId')
    temfile = Managelogin.objects.get(uid=temid)
    json_lm = {"code": 0}
    json_lm["data"] = eval(temfile.mfile)
    return JsonResponse(json_lm)

##‘127.0.0.1:8000/hulin/data/signin'   获取签到列表
def get_signin(request):
    temid = request.GET.get('rangerId')
    temfile = Signin.objects.get(uid=temid)
    json_si = {"code":0}
    json_si["data"] = {"list":eval(temfile.lfile)}
    return JsonResponse(json_si)

##‘127.0.0.1:8000/hulin/supsign'   补签
def sup_sign(request):
    data = json.loads(request.body)
    temd = Signin.objects.get(uid = data["rid"])
    temf = eval(temd.lfile)
    temf.append(data["date"])
    temd.lfile = temf
    temd.save()
    return JsonResponse({"code":0,"msg":"补签成功"})

##‘127.0.0.1:8000/hulin/data/analysis'   数据分析
def get_data(request):
    temdate = str(datetime.datetime.now())[0:10]
    json_re = {"code":0}
    list_weather = []
    json_an={}
    lis_me=[Mession.objects.filter(stime__startswith = temdate,status = '已完成').count(),Mession.objects.filter(stime__startswith = temdate).count()]
    lis_ev=[Event.objects.filter(stime__startswith = temdate,status = '已处理').count(),Event.objects.filter(stime__startswith = temdate).count()]
    lis_re=[Ranger.objects.all().count()-Ranger.objects.filter(status = '在岗').count(),Ranger.objects.all().count()]
    a = ['林区整体','林区中部','邻区东部','林区西部','林区南部','邻区北部']
    dstart = int(temdate[8:])-6
    for j in a :
        tem_js = {"area":j,"list":[]}
        for i in range(7):
            ddd = temdate[:8]+'%.2d' % (dstart+i)
            tem = Forest.objects.get(area = j,datee = ddd)
            tem_js["list"].append({"date":tem.datee,"info":eval(tem.weather)})
        list_weather.append(tem_js)
    json_an["mession"] =lis_me
    json_an["event"] = lis_ev
    json_an["ranger"] =lis_re
    json_re["data"] = {"weather":list_weather,"analysis":json_an}
    return JsonResponse(json_re)



#‘127.0.0.1:8000/hulin/add/event'   上报事件
def add_event(request):
    rid = int(request.GET.get('rid'))
    data = json.loads(request.body)
    temnum = Event.objects.filter(rid=rid).count()
    if temnum == 0:
        temid = rid * 1000+200
    else:
        temid = Event.objects.filter(rid=rid)[temnum - 1].id + 1
    temtime = str(datetime.datetime.now())[0:19]
    Event.objects.create(id=temid, title=data["title"], content=data["content"], x=data["x"], y=data["y"],
                           mclass=data["class"],
                           status='待处理', stime=temtime, rid=rid, mid=rid//100)

    # 管理员记录记录
    temmid = rid//100
    temman = Managelogin.objects.get(uid=temmid)
    j_temman = eval(temman.mfile)
    j_temman[temtime] = '%s(%d)向我(%d)上报了事件-%s' % (Ranger.objects.get(uid=rid).name, rid, temmid, data["title"])
    temman.mfile = json.dumps(j_temman, ensure_ascii=False)
    temman.save()
    return JsonResponse({"1":1})

#‘127.0.0.1:8000/hulin/add/jurnal'   添加日志
def add_jurnal(request):
    rid = int(request.GET.get('rid'))
    data = json.loads(request.body)
    temnum = Rjurnal.objects.filter(rid=rid).count()
    if temnum == 0:
        temid = rid * 1000 + 100
    else:
        temid = Rjurnal.objects.filter(rid=rid)[temnum - 1].id + 1
    temtime = str(datetime.datetime.now())[0:19]
    Rjurnal.objects.create(id = temid,rid = rid,time = temtime,content = data["content"])
    return JsonResponse({"1": 1})

#‘127.0.0.1:8000/hulin/fin/mession'   完成任务
def fin_mession(request):
    messionid = int(request.GET.get('messionId'))
    temme = Mession.objects.get(id = messionid)
    temr = Ranger.objects.get(uid = temme.rid)
    temtime = str(datetime.datetime.now())[0:19]
    temme.ftime=temtime
    temme.status = "已完成"
    temme.save()
    if temr.num == 1:
        temr.num = 0
        temr.status = "在岗"
        temr.save()
    else:
        temr.status = '%d个任务进行中' % (temr.num - 1)
        temr.num = temr.num-1
        temr.save()
    # 管理员记录记录
    temmid = temr.uid//100
    temman = Managelogin.objects.get(uid=temmid)
    j_temman = eval(temman.mfile)
    j_temman[temtime] = '%s(%d)完成了我(%d)发布的任务-%s' % (temr.name, temr.uid, temmid, temme.title)
    temman.mfile = json.dumps(j_temman, ensure_ascii=False)
    temman.save()
    return JsonResponse({"1": 1})

